//
//  NSString+SYAdd.m
//  SYSDK
//
//  Created by ligq on 2020/4/13.
//  Copyright © 2020 synjones. All rights reserved.
//

#import "NSString+SYAdd.h"
#import <CoreText/CoreText.h>

@implementation NSString (SYAdd)

- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize {
    
    NSDictionary *textAttrs = @{NSFontAttributeName : font};
    
    CGSize trueSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil].size;
    
    return CGSizeMake(trueSize.width, trueSize.height);
}

- (CGFloat)heightWithFont:(CGFloat)font width:(CGFloat)width LineSpace:(CGFloat)lineSpace{
    
    
    CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
//    if (lineSpace == 0) {
//
//        NSDictionary *textAttrs = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
//        CGSize trueSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil].size;
//        CGFloat height = trueSize.height;
//
//        return height;
//    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font], NSParagraphStyleAttributeName:paragraphStyle}];
    
    CGSize trueSize = [attributedString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
//    //row number
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([[UIFont systemFontOfSize:font] fontName]), [[UIFont systemFontOfSize:font] pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,maxSize.width,maxSize.height));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
//    NSLog(@"%lu",(unsigned long)lines.count);
    CGFloat height = trueSize.height;
//
    if (lines.count > 2) {
        height -= 12;
    }
    
    return height;
    
}

- (NSMutableAttributedString *)attributedStringWithRangeArray:(NSArray *)rangeArray fontArray:(NSArray *)fontArray colorArray:(NSArray *)colorArray lineSpacing:(CGFloat)lineSpacing{
    
    // 如果range数组为空，直接返回自己
    if (rangeArray.count == 0) {
        return [[NSMutableAttributedString alloc] initWithString:self attributes:nil];
    }
    
    // 如果数组元素个数不一致，直接把返回自己
    if ((rangeArray.count != fontArray.count) || (rangeArray.count != colorArray.count)) {
        return [[NSMutableAttributedString alloc] initWithString:self attributes:nil];
    }
    
    // 带属性字符串
    NSMutableAttributedString *attrContent = [[NSMutableAttributedString alloc] initWithString:self];
    
    for (int i = 0; i < rangeArray.count; i++) {
        // 获取range
        NSDictionary *dict = (NSDictionary *)rangeArray[i];
        NSString *location = (NSString *)dict[@"location"];
        NSString *length = (NSString *)dict[@"length"];
        
        // range
        NSRange range = NSMakeRange(location.intValue, length.intValue);
        
        // 字体大小
        [attrContent addAttribute:NSFontAttributeName value:fontArray[i] range:range];
        
        // 字体颜色
        [attrContent addAttribute:NSForegroundColorAttributeName value:colorArray[i] range:range];
    }
    
    // 内容行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.alignment = NSTextAlignmentRight;
    
    [attrContent addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.length)];
    
    return attrContent;
}

- (NSMutableAttributedString *)attributedStringWithRangeArray:(NSArray *)rangeArray fontArray:(NSArray *)fontArray colorArray:(NSArray *)colorArray{
    
    return [self attributedStringWithRangeArray:rangeArray fontArray:fontArray colorArray:colorArray lineSpacing:0];
}

- (instancetype)jx_substringToIndex:(NSUInteger)index {
    
    return self.length >= index ? [self substringToIndex:index] : self;
}

- (instancetype)replaceSemicolonToLineBreak {
    
    if ([self containsString:@"\n"]) {
        return self;
    }

    NSString *string = [self stringByReplacingOccurrencesOfString:@"；" withString:@"\n"];
    NSString *string2 = [string stringByReplacingOccurrencesOfString:@";" withString:@"\n"];
    return string2;
}

- (instancetype)clearSpace {
    
    NSString *string = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    return string;
}

- (instancetype)filterSpecialCharacter {
    //英文字符集合
    NSCharacterSet *letterCharacterSet = [NSCharacterSet letterCharacterSet];
    //中文字符集合
    NSCharacterSet *chineseSet = [self chineseSet];
    
    //合法字符  英文字符 中文字符 并集的集合
    NSMutableCharacterSet *characterSet  = [[NSMutableCharacterSet alloc] init];
    [characterSet formUnionWithCharacterSet:letterCharacterSet];
    [characterSet formUnionWithCharacterSet:chineseSet];
    
    // 除去合法字符  英文字符 中文字符 并集的集合的补集
    NSCharacterSet *illegalCharacterSet = characterSet.invertedSet;
    
    // 将非法字符过滤成 @""
    NSString *legalNickName = [[self componentsSeparatedByCharactersInSet:illegalCharacterSet] componentsJoinedByString:@""];
    
    return legalNickName;
}

- (instancetype)numberOrWord {
    
    //字母和数字的字符集
    NSMutableCharacterSet *characterSet  = [NSMutableCharacterSet alphanumericCharacterSet];
    NSCharacterSet *illegalCharacterSet = characterSet.invertedSet;
    
    // 将非法字符过滤成 @""
    NSString *legalCardNumber = [[self componentsSeparatedByCharactersInSet:illegalCharacterSet] componentsJoinedByString:@""];
    
    return legalCardNumber;
}

- (instancetype)numberMake {
    
    //数字的字符集
    NSMutableCharacterSet *characterSet  = [NSMutableCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *illegalCharacterSet = characterSet.invertedSet;
    
    // 将非法字符过滤成 @""
    NSString *legalCardNumber = [[self componentsSeparatedByCharactersInSet:illegalCharacterSet] componentsJoinedByString:@""];
    
    return legalCardNumber;
}

- (NSCharacterSet *)chineseSet {
    // 中文字符集合
    static NSCharacterSet *chineseSet;
    if (chineseSet == nil)
    {
        NSMutableCharacterSet *aCharacterSet = [[NSMutableCharacterSet alloc] init];
        
        NSRange lcEnglishRange;
        lcEnglishRange.location = (unsigned int)0x4e00;
        lcEnglishRange.length = (unsigned int)0x9fa5 - (unsigned int)0x4e00;
        [aCharacterSet addCharactersInRange:lcEnglishRange];
        chineseSet = aCharacterSet;
    }
    return chineseSet;
}

- (instancetype)filterEmoji {
    //去除表情规则
    NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSString *result = [expression stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, self.length) withTemplate:@""];
    
    return result;
}

- (int)bytesCount
{
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    return [self bytesCountWithEncoding:encoding];
}

- (int)bytesCountWithEncoding:(NSStringEncoding)encoding
{
    int strLength = 0;
    char *p = (char *)[self cStringUsingEncoding:encoding];
    
    NSUInteger lengthOfBytes = [self lengthOfBytesUsingEncoding:encoding];
    for (int i = 0; i < lengthOfBytes; i++) {
        if (*p) {
            p++;
            strLength++;
        }
        else {
            p++;
        }
    }
    return strLength;
}

- (instancetype)retainTwoDecimalPlaces {
    return [self retainDecimalPlacesWithPlacesNumber:2];
}

- (instancetype)retainDecimalPlacesWithPlacesNumber:(NSInteger)placesNumber {
    
    NSString *result = [NSString string];
    if ([self containsString:@"."]) {
        NSRange dotRange = [self rangeOfString:@"."];
        if ((dotRange.location + placesNumber + 1) <= self.length) {
            result = [self substringWithRange:NSMakeRange(0, dotRange.location + placesNumber + 1)];
        }
        else {
            NSInteger deviation = dotRange.location + placesNumber + 1 - self.length;
            result = self;
            for (int i = 0; i < deviation; i++) {
                result = [NSString stringWithFormat:@"%@0", result];
            }
        }
    }
    else {
        result = [NSString stringWithFormat:@"%@.", self];
        for (int i = 0; i < placesNumber; i++) {
            result = [NSString stringWithFormat:@"%@0", result];
        }
    }
    
    return result;
}

- (instancetype)spell {
    
    NSMutableString *ms = [[NSMutableString alloc]initWithString:self];
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0,kCFStringTransformMandarinLatin, NO)) {
    }
    // 去除拼音的音调
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0,kCFStringTransformStripDiacritics, NO)) {
        if (self.length) {
            NSString *bigStr = [ms uppercaseString];
            NSString *cha = [bigStr substringToIndex:1];
            return cha;
        }
    }
    return self;
}

- (NSString *)stringByreplaceingHtmlImagUrlString:(NSString *)html{
    NSString *imageSize = [NSString stringWithFormat:@"%dx%d",1000,1000];
    if ([html containsString:@".jpg"]) {
        html = [html stringByReplacingOccurrencesOfString:@".jpg" withString:[NSString stringWithFormat:@".jpg_%@.jpg",imageSize]];
    }
    if ([html containsString:@".png"]) {
        html = [html stringByReplacingOccurrencesOfString:@".png" withString:[NSString stringWithFormat:@".png_%@.png",imageSize]];
    }
    if ([html containsString:@".jpeg"]) {
        html = [html stringByReplacingOccurrencesOfString:@".jpeg" withString:[NSString stringWithFormat:@".jpeg_%@.jpeg",imageSize]];
    }
    if ([html containsString:@".gif"]) {
        html = [html stringByReplacingOccurrencesOfString:@".gif" withString:[NSString stringWithFormat:@".gif_%@.gif",imageSize]];
    }
    
    return html;
}

@end
